<template>
	<view class="" :style="{height: menuTopHeight + 'px'}"></view>
	<view class="menu-box" :style="{height: menuHeight + 'px'}">
		<u-icon name="arrow-left" color="#222222" size="20" @click="goBack"></u-icon>
		<view class="navigate-title">购物车</view>
		<view class="delete" @tap="showCancelPop">删除</view>
	</view>
	<view class="container">
		<!-- 购物车列表 -->
		<view class="car-list" v-if="carList.length > 0">
			<u-checkbox-group v-model="checkboxValue" placement="column"  @change="checkboxChange">
				<view :style="{marginBottom: i == (carList.length - 1) ? '0' : '60rpx'}" class="car-item"
					v-for="(item, i) in carList" :key="i">
					<view class="check">
						<u-checkbox activeColor="#516DDB" shape="circle" :checked="item.checked" :key="i" :name="item.id">
						</u-checkbox>
					</view>
					<view class="img-box" @click="goStoreDetail($event, item.product_id)">
<!--						<u-image radius="20rpx" width="170rpx" height="155rpx" src="/static/logo.png"></u-image>-->
						<u-image radius="20rpx" width="170rpx" height="155rpx" :src="checkAndFixUrl(item?.product?.cover ?? '')" mode="aspectFit"></u-image>
					</view>
					<view class="car-content">
						<view class="title">
							{{ item.product.name }}
						</view>
						<view class="price-num">
							<view class="price-box">
								<text class="yuan">￥</text>
								<text class="price">{{ item.sku.price }}</text>
							</view>
							<view class="num-box">
								<u-number-box min="1" v-model="item.quantity" :asyncChange="true" @change="handleChangeQuantity($event,i,item)">
									<template #minus>
										<view class="minus">
											<u-image width="48rpx" height="48rpx" :src="getServerStatic('/static/images/a66.png')"></u-image>
										</view>
									</template>
									<template #input>
										<text style="width: 50px;text-align: center;" class="input">{{ item.quantity }}</text>
									</template>
									<template #plus>
										<view class="plus">
											<u-image width="48rpx" height="48rpx" :src="getServerStatic('/static/images/a67.png')" ></u-image>
										</view>
									</template>
								</u-number-box>
							</view>
						</view>
					</view>
				</view>
			</u-checkbox-group>
		</view>
        <!-- 无数据 -->
        <view class="empty-box" v-else>
            <u-empty textColor="#516DDB" text="暂无商品~" mode="data" :icon="getServerStatic('/static/images/empty.png')">
            </u-empty>
        </view>

		<!-- 九宫格 -->
        <view class="grid-wrap" v-for="(label, index) in labelProducts" :key="index">
			<view class="title-box">
				<u-image width="34rpx" height="30rpx" :src="getServerStatic('/static/images/a64.png')"></u-image>
				<view class="title">{{ label.name }}</view>
				<u-image width="34rpx" height="30rpx" :src="getServerStatic('/static/images/a64.png')"></u-image>
			</view>
			<u-grid :border="false" col="3" @click="goStoreDetail">
                <u-grid-item v-for="(item, i) in label.products" :key="i" @click="goStoreDetail($event, item.id)">
					<view class="commodity-item grid-bottom">
						<view class="img-box">
                            <u-image width="220rpx" height="200rpx" :src="checkAndFixUrl(item?.cover ?? '')" mode="aspectFit"></u-image>
                        </view>
						<view class="content-box">
							<view class="title">{{ item.name }}</view>
							<view class="price-box">
								<view class="price">￥{{ item.price }}</view>
								<view class="icon-box" @tap.stop="showPop($event, item)">
									<u-image width="44rpx" height="44rpx" :src="getServerStatic('/static/images/a63.png')"></u-image>
								</view>
							</view>
						</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
	</view>

	<!-- 底部结算按钮 -->
	<view class="buy-wrap">
		<view class="buy-btn-wrap">
			<view class="all-select">
				<u-checkbox shape="circle" activeColor="#516DDB" label="全选" @change="allSelectChange"></u-checkbox>
			</view>
			<view class="left">
				<view class="name">合计</view>
				<view class="price-box">
					<text class="yuan">￥</text>
					<text class="price">{{ total }}</text>
				</view>
			</view>
			<view class="right">
				<u-button throttleTime="1000" :customStyle="{height: '80rpx', letterSpacing: '.1rem', width: '250rpx'}"
					:hairline="false" type="mini" shape="circle" color="#516DDB" @click="goSuccess">去结算</u-button>
			</view>
		</view>
	</view>

    <!-- 选择规格弹窗组件 -->
    <SelectSku ref="selectSkuRef"
               :productAttrs="productAttrs"
               :productSkus="productSkus"
               :productInfo="productInfo"
               @confirmSku="confirmSku"
    >
    </SelectSku>


	<!-- 删除模态框 -->
	<u-modal showCancelButton :show="cancelPop" title="删除商品" @cancel="cancelPop = false" @confirm="handleRemoveItem"
		confirmColor="#516DDB">
		<view class="tip">是否要确定删除该商品？</view>
	</u-modal>
</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow} from '@dcloudio/uni-app'
	import {
		useHeight
	} from '@/hooks/useMenuHeight'
    import {deleteProduct, getCartList, storeCart, updateQuantity} from "@/api/cart";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    import {getLabels, getProductDetail} from "@/api/product";
    import SelectSku from '@/components/SelectSku'
	const {
		menuHeight,
		menuTopHeight
	} = useHeight()

    const selectSkuRef = ref(null)
	const cancelPop = ref(false)
	const checkboxValue = ref([]);
	const carList = ref([])

    onLoad((evt) => {
        console.log('购物车列表', evt)

        // 获取购物车列表
        handleGetCartList()

        // 获取推荐标签
        handleGetLabels()
    })

    // 购物车列表
    const handleGetCartList = async () => {
        uni.showLoading({
            title: '加载中'
        });
        const {code, data} = await getCartList({})
        uni.hideLoading();

        if (code === 1) {
            carList.value = data.map(item => {
                return {
                    ...item,
                    checked: false
                }
            })
        }
    }

    // 标签商品
    const labelProducts = ref([])
    const handleGetLabels = async () => {
        const {code, data} = await getLabels({recommend: 1})
        if (code == 1) {
            labelProducts.value = data
        }
    }

    // 更新数量
    const handleChangeQuantity = async (e, index, item) => {
        const param = {
            cart_id: item.id,
            sku_id: item.product_sku_id,
            quantity: e.value
        }
        // console.log(e)
        // console.log(index)
        // console.log(item)
        const {code, data, message} = await updateQuantity(param)
        if (code !== 1) {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        } else {
            carList.value[index].quantity = e.value
        }
    }

    // 商品复选框
    // 单个选中
    const checkboxChange = (idsToCheck) => {
        console.log('change', idsToCheck);

        // 遍历数组将所有checked值设置为false
        carList.value.forEach(item => {
            item.checked = false;
        });

        // 遍历条件数组并修改对应对象的checked值
        idsToCheck.forEach(id => {
            let itemToUpdate = carList.value.find(item => item.id === id);
            if (itemToUpdate) {
                itemToUpdate.checked = true;
            }
        });

        handleChangeSelected()
    }

    const checkedIdsRef = ref([])
	// 删除
	const showCancelPop = () => {
        // 获取选中的商品
        let checkedElements = carList.value.filter(item => item.checked);
        // 返回ID
        let checkedIds = checkedElements.map(item => item.id);
        if (checkedIds.length <= 0) {
            uni.showModal({
                title: '提示',
                content: "请至少选择一项",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
            return
        }
        checkedIdsRef.value = checkedIds
		cancelPop.value = true
	}

    const handleRemoveItem = async () => {
        console.log('ids', checkedIdsRef.value)
        cancelPop.value = false
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await deleteProduct({cart_ids: checkedIdsRef.value})
        uni.hideLoading();

        if (code === 1) {
            await handleGetCartList()
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {

                }
            });
        }
    }

	// 全选
	const allSelectChange = e => {
		console.log(e);
        if (!e) {
            carList.value.forEach((item,index) => {
                item.checked = false;
            })
        } else {
            // 设置全部选中
            carList.value.forEach((item,index) => {
                item.checked = true;
            })
        }

        handleChangeSelected()
	}

    // 总金额
    const total = ref(0)

    // 选中变化
    const handleChangeSelected = () => {
        // 计算金额
        // 将金额乘以100以转换为整数
        let totalAmount = carList.value.reduce((accumulator, item) => {
            if (item.checked) {
                accumulator += Math.round(item.sku.price * 100) * item.quantity;
            }
            return accumulator;
        }, 0);

        totalAmount /= 100;
        console.log('总金额:', totalAmount)
        total.value = totalAmount
    }

	// 支付成功
	const goSuccess = () => {

        // 获取选中的商品
        let checkedElements = carList.value.filter(item => item.checked);
        // 返回ID
        let checkedIds = checkedElements.map(item => item.id);
        if (checkedIds.length <= 0) {
            uni.showModal({
                title: '提示',
                content: "请至少选择一项",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
            return
        }

        let cartIdsStr = checkedIds.join(',')
        console.log('cart_ids', cartIdsStr)
        uni.navigateTo({
            url: `/mine/drug-store/confirm?type=cart&cart_ids=${cartIdsStr}`
        })

		// uni.navigateTo({
		// 	url: '/mine/reservation/success'
		// })
	}
	// 返回
	const goBack = () => {
		uni.navigateBack()
	}

    // 商品属性
    const productAttrs = ref([])
    // 商品规格
    const productSkus = ref([])
    // 商品信息
    const productInfo = ref([])

    // 展示规格
    const showPop = async (event,item) => {
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await getProductDetail({product_id: item.id})
        uni.hideLoading();

        if (code == 1) {
            productInfo.value = data?.product ?? {}
            productAttrs.value = data?.product?.attrs ?? []
            productSkus.value = data?.product?.skus ?? []
            console.log('商品属性',productAttrs.value)
            console.log('商品SKU',productSkus.value)
            selectSkuRef.value.open()

        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }

    // 确认sku 加入购物车
    const confirmSku = async (result) => {
        console.log(result)
        console.log('选择的sku', result.sku.attr_name)
        // 加入购物车
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await storeCart({sku_id: result.sku.id, quantity: result.quantity })
        uni.hideLoading();

        if (code === 1) {
            await handleGetCartList()
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }

    }

    // 商品详情
    const goStoreDetail = (e, productId) => {
        if (productId) {
            uni.navigateTo({
                url: `/mine/drug-store/detail?product_id=${productId}`
            })
        }
    }
</script>

<style lang="scss" scoped>
	.menu-box {
		padding-left: 26rpx;
		display: flex;
		// align-items: flex-end;
		align-items: center;

		.navigate-title {
			color: #222222;
			font-size: 36rpx;
			margin-left: 18rpx;
		}

		.delete {
			margin-left: 40rpx;
			color: #666666;
			font-size: 28rpx;
		}
	}

	.container {
		padding: 0 26rpx 200rpx;
	}

    .empty-box {
        @include center(100%, 50vh);
        padding: 40rpx 26rpx;
        background: #FFFFFF;
    }

	.car-list {
		padding: 40rpx 26rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		margin-top: 52rpx;

		.car-item {
			// margin-bottom: 60rpx;
			@include between(100%);

			.img-box {
				margin: 0 16rpx 0 6rpx;
			}

			.car-content {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				height: 155rpx;

				.title {
					color: #333333;
					@include more-over-ellip(2);
				}

				.price-num {
					@include between(100%);

					.price-box {
						color: #F55726;

						.yuan {
							font-size: 28rpx;
						}

						.price {
							font-weight: bold;
							font-size: 40rpx;
						}
					}
				}
			}
		}
	}

	.grid-wrap {
		margin-top: 40rpx;

		.title-box {
			@include center();
			color: #516DDB;
			font-size: 36rpx;
			margin-bottom: 30rpx;

			.title {
				margin: 0 48rpx;
			}
		}

		.grid-bottom {
			margin-bottom: 30rpx;
		}

		.commodity-item {
			position: relative;
			width: 220rpx;
			// height: 330rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			margin-right: 20rpx;
			overflow: hidden;
			box-shadow: 0rpx 0rpx 10rpx 1rpx rgba(102, 102, 102, 0.16);
			z-index: 99;

			.content-box {
				padding: 8rpx 8rpx 15rpx;

				.title {
					color: #666666;
					@include over-ellip();
					margin-bottom: 12rpx;
				}

				.price-box {
					@include between(100%);

					.price {
						font-size: 28rpx;
						color: #F55726;
					}

					.icon-box {
						@include center(44rpx, 44rpx);
						background: #516DDB;
						border-radius: 50%;
					}
				}
			}
		}
	}

	.buy-wrap {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding-top: 21rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
		box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0, 0, 0, 0.1);
		background: #FFFFFF;
		z-index: 99;

		.buy-btn-wrap {
			@include between(100%);

			.left {
				display: flex;
				align-items: center;

				.name {
					color: #000000;
					margin-right: 14rpx;
				}

				.price-box {
					color: #333333;

					.price {
						font-weight: bold;
						font-size: 32rpx;
					}
				}
			}
		}
	}
</style>
